package com.jjr.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;

import tool.IdcardValidator;
import tool.TimeTool;

import com.base.bean.*;
import com.base.dao.*;
import com.jjr.bean.*;

public class JingJiRenService {
	// 单例模式 start
	private volatile static JingJiRenService instance = null;

	private JClientDao cdao;
	private JClientPhoneDao jpdao;
	private ClientPhoneDao cpdao;
	private JUserDao udao;
	private ClientBaseDao cbdao;

	private JingJiRenService() {
		cdao = (JClientDao) _BaseDao.ac.getBean("JClientDao");
		jpdao = (JClientPhoneDao) _BaseDao.ac.getBean("JClientPhoneDao");
		cpdao = (ClientPhoneDao) _BaseDao.ac.getBean("ClientPhoneDao");
		udao = (JUserDao) _BaseDao.ac.getBean("JUserDao");
		cbdao = (ClientBaseDao) _BaseDao.ac.getBean("ClientBaseDao");
	}

	public static JingJiRenService getInstance() {
		if (instance == null) {
			synchronized (JingJiRenService.class) {// 1
				if (instance == null) {// 2
					instance = new JingJiRenService();// 3
				}
			}
		}
		return instance;
	}

	// 单例模式 end

	// test
	public static void main(String[] args) {
		JingJiRenService s = new JingJiRenService();
		Timestamp now = TimeTool.getCurrentTime();
//		JClient jc = new JClient("张三", "510000", "510010", "510001", "成都",
//				"四川", "成华区", "comName", 1, 1, TimeTool.getCurrentTime(),
//				TimeTool.getCurrentTime(), "gmsbType", 1, "wjjpp", "zzjpp",
//				"memo", 0, 0);
//		jc.setId(-11); // 0 add >0 modify <0 delete
//		JClientPhone p1 = new JClientPhone(-10, 15, "17000000004", now); // 0
//																			// add
//																			// >0
//																			// modify
//																			// <0
//																			// delete
//		JClientPhone p2 = new JClientPhone(-11, 15, "17000000003", now);
//		List<JClientPhone> jcpList = new ArrayList<JClientPhone>();
//		jcpList.add(p1);
//		jcpList.add(p2);
//
//		JClientDetail jcd = new JClientDetail();
//		jcd.setjClient(jc);
//		jcd.setJpList(jcpList);
//
//		JsonResult r = s.mergeJClient(jcd);
//		System.out.println(r.getTip());
		
		JUser user = new JUser();
		user.setName("will");
		user.setPhone("15982079516");
		s.mergeJUser(user);
		

	}

	// －－－－－－－－－－－－－－－ 分割线 －－－－－－－－－－－－－－－－－－－－－－－－

	public Integer getUidByOpenId(String openId){
	try{	
		JUser user = this.udao.findByHql("from JUser a where a.openId='"+openId+"'").get(0);
		return user.getId();
	}catch(Exception e){
		e.printStackTrace();
		return 0;
	}
	
	
	}
	
	
	public JsonResult mergeJUser(JUser user) {
		
		
		JsonResult r = new JsonResult();
		boolean checked = true;
		boolean checked2 = true;
		
		
		
		//检查必填项
		if(user.getName().equals("") || user.getPhone().equals("") || user.getArea().equals("")
				|| user.getProvince().equals("") || user.getCity().equals("") ){
			checked= checked && false;
			
		}
		
		//检查身份证
		String idCard = user.getIdCard();
		idCard = idCard.replaceAll("\\s*", "");
		checked2= IdcardValidator.getInstance().isValidatedAllIdcard(idCard);
		
		if((checked==false) || (checked2 ==false)){
			r.setState(-1);
			r.setTip("请检查必填项");
			return r;
		}
		
		// 保存信息
		Integer uid = user.getId();
		if(uid==0){	// 新增
			this.udao.merge(user);
			r.setTip("操作成功");
			r.setState(1);
			
		}else if(uid>0){	//修改 修改后需要重新审核
			user.setState(0);
			this.udao.merge(user);
			r.setTip("操作成功，由于修改了信息后台正在重新审核中");
			r.setState(1);
		}
		
		return r;
			
	}

	
	/**
	 * jcd:JClient:id 三态来决定add modify delete jcd:phone 一样
	 * 
	 * @param jcd
	 * @return
	 */
	public JsonResult mergeJClient(JClientDetail jcd) {
		JsonResult r = new JsonResult();

		Integer cid = jcd.getJClient().getId();
		List<JClientPhone> phoneList = jcd.getJpList();

		Session session = null;
		Transaction tx = null;
		try {
			session = this.cdao.getSessionFactory().getCurrentSession();
			tx = session.beginTransaction();

			boolean repeat = false;

			if (cid == 0) { // 新增客户
				session.save(jcd.getJClient());
				// 查询max cid
				@SuppressWarnings("unchecked")
				List<Integer> results = session
						.createCriteria(JClient.class)
						.setMaxResults(1)
						.setProjection(
								Projections.projectionList().add(
										Projections.max("id"))).list();
				cid = results.get(0);
				int i = 0;
				for (JClientPhone p : phoneList) {
					i = i + 1;
					// 查询电话是否重复
					// 查询电话是否已经存在
					Integer count1 = Integer
							.parseInt(session
									.createSQLQuery(
											"SELECT count(*) FROM client_phone cp  WHERE cp.phone= :phone")
									.setString("phone", p.getPhone())
									.uniqueResult().toString());
					Integer count2 = Integer
							.parseInt(session
									.createSQLQuery(
											"SELECT count(*) FROM j_clientPhone jcp  WHERE jcp.phone= :phone")
									.setString("phone", p.getPhone())
									.uniqueResult().toString());

					if ((count1 > 0) || (count2 > 0)) {
						repeat = repeat || true;
						r.setTip("该电话号码已经存在(电话" + i + ")");
						break;
					}

					p.setAccountId(cid);
					session.save(p);
				}

			} else if (cid > 0) { // 修改客户
				session.merge(jcd.getJClient());
				for (JClientPhone p : phoneList) { // 更新电话
					Integer pid = p.getId();
					if (pid == 0) {
						session.save(p);
					} else if (pid > 0) {
						session.merge(p);
					} else if (pid < 0) {
						p.setId(Math.abs(p.getId()));
						session.delete(p);
					}

				}

			} else if (cid < 0) { // 作废客户
				Integer _cid = Math.abs(cid);
				String hqlDelete1 = "delete JClientPhone a where a.accountId= :accountId";
				// or String hqlDelete =
				// "delete Customer where name = :oldName";
				int deletedEntities = session.createQuery(hqlDelete1)
						.setInteger("accountId", _cid).executeUpdate();

				String hqlDelete2 = "delete JClient b where b.id= :id";
				int deletedEntities2 = session.createQuery(hqlDelete2)
						.setInteger("id", _cid).executeUpdate();

			}

			if (!repeat) {
				tx.commit();
				r.setState(1);
				r.setTip("操作成功");

			}
			return r;
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
			r.setState(-1);
			r.setTip("服务器或网络异常");
			return r;
		}

		finally {
			if (session.isOpen())
				session.close();
		}
	}

	// －－－－－－－－－－－－－－－ 分割线 －－－－－－－－－－－－－－－－－－－－－－－－

	public JClientDao getCdao() {
		return cdao;
	}

	public JClientPhoneDao getJpdao() {
		return jpdao;
	}

	public ClientPhoneDao getCpdao() {
		return cpdao;
	}

	public JUserDao getUdao() {
		return udao;
	}

	public ClientBaseDao getCbdao() {
		return cbdao;
	}

}
